<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>AI Chat</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 h-screen">
<div class="flex h-full">
    <!-- 左侧边栏 -->
    <div class="w-64 bg-white border-r p-4 flex flex-col">
        <button onclick="createNewChat()" class="bg-blue-500 text-white p-2 rounded mb-4 hover:bg-blue-600">
            新建聊天
        </button>
        <div id="chat-list" class="flex-1 overflow-y-auto space-y-2"></div>
    </div>

    <!-- 主聊天区域 -->
    <div class="flex-1 flex flex-col">
        <!-- 对话列表 -->
        <div id="message-container" class="flex-1 overflow-y-auto p-4 space-y-4"></div>

        <!-- 输入区域 -->
        <div class="p-4 border-t bg-white">
            <div class="flex space-x-2">
                <input id="message-input" type="text"
                       class="flex-1 p-2 border rounded"
                       placeholder="输入消息..."
                       onkeydown="handleKeyDown(event)">
                <button onclick="sendMessage()"
                        class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600">
                    发送
                </button>
            </div>
        </div>
    </div>
</div>

<script>
    let chats = [];
    let currentChatId = null;
    let eventSource = null;

    // 初始化示例聊天
    createNewChat();

    function createNewChat() {
        const chatId = Date.now().toString();
        const newChat = {
            id: chatId,
            name: `对话 ${chats.length + 1}`,
            messages: []
        };
        chats.push(newChat);
        currentChatId = chatId;
        renderChatList();
        renderMessages();
    }

    function renderChatList() {
        const container = document.getElementById('chat-list');
        container.innerHTML = chats.map(chat => `
            <div class="group flex items-center justify-between p-2 rounded cursor-pointer
                        ${currentChatId === chat.id ? 'bg-blue-100' : 'hover:bg-gray-100'}"
                 onclick="selectChat('${chat.id}')">
                <span>${chat.name}</span>
                <div class="opacity-0 group-hover:opacity-100 flex space-x-1">
                    <button onclick="renameChat('${chat.id}')" class="text-gray-500 hover:text-blue-500">✏️</button>
                    <button onclick="deleteChat('${chat.id}')" class="text-gray-500 hover:text-red-500">🗑️</button>
                </div>
            </div>
        `).join('');
    }

    function selectChat(chatId) {
        currentChatId = chatId;
        renderChatList();
        renderMessages();
    }

    function deleteChat(chatId) {
        chats = chats.filter(chat => chat.id !== chatId);
        if (currentChatId === chatId) {
            currentChatId = chats[0]?.id;
        }
        renderChatList();
        renderMessages();
    }

    function renameChat(chatId) {
        const newName = prompt('输入新对话名称:');
        if (newName) {
            const chat = chats.find(c => c.id === chatId);
            chat.name = newName;
            renderChatList();
        }
    }

    function renderMessages() {
        const container = document.getElementById('message-container');
        const chat = chats.find(c => c.id === currentChatId);
        container.innerHTML = chat.messages.map(msg => `
            <div class="${msg.role === 'user' ? 'text-right' : 'text-left'}">
                <div class="inline-block p-3 rounded-lg
                          ${msg.role === 'user' ? 'bg-blue-500 text-white' : 'bg-gray-200'}">
                    ${msg.content}
                </div>
            </div>
        `).join('');
    }

    async function sendMessage() {
        const input = document.getElementById('message-input');
        const message = input.value.trim();
        if (!message) return;

        // 添加用户消息
        const chat = chats.find(c => c.id === currentChatId);
        chat.messages.push({ role: 'user', content: message });
        input.value = '';
        renderMessages();

        // 添加AI消息占位
        const aiMessage = { role: 'assistant', content: '' };
        chat.messages.push(aiMessage);
        renderMessages();

        // 滚动到底部
        const container = document.getElementById('message-container');
        container.scrollTop = container.scrollHeight;

        // 发起流式请求
        if (eventSource) eventSource.close();
        const apiUrl = `http://localhost:8090/api/v1/ollama/generate_stream?model=deepseek-r1:1.5b&message=${encodeURIComponent(message)}`;

        eventSource = new EventSource(apiUrl);
        let fullContent = '';

        eventSource.onmessage = (event) => {
            try {
                const data = JSON.parse(event.data);
                const content = data.result?.output?.content || '';
                const finishReason = data.result?.metadata?.finishReason;

                fullContent += content;

                // 更新最后一条消息
                aiMessage.content = fullContent;
                renderMessages();
                container.scrollTop = container.scrollHeight;

                if (finishReason === 'STOP') {
                    eventSource.close();
                }
            } catch (e) {
                console.error('解析错误:', e);
            }
        };

        eventSource.onerror = (err) => {
            console.error('EventSource错误:', err);
            eventSource.close();
        };
    }

    function handleKeyDown(event) {
        if (event.key === 'Enter' && !event.shiftKey) {
            event.preventDefault();
            sendMessage();
        }
    }
</script>
</body>
</html>